var stats = new Stats(),
    c = document.getElementById('c'),
    ctx = c.getContext('2d');
window.addEventListener('resize', handleWindowResize, false);
function handleWindowResize() {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
}
handleWindowResize();

var GRAVITY_FORCE = 9.81,
    PLATFORM_HEIGHT_IN_METER = 10, //将整个canvas的高看做10M
    pixelsPerMeter = c.height / PLATFORM_HEIGHT_IN_METER, //每米的像素数
    fps, frameAnimationId;

var ballParam = {
    radius: 50
}
function drawBall (sprite, ctx) {
    ctx.save();
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(sprite.x, sprite.y, ballParam.radius, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}
var fillBallPaint = new Sprite.StrokeAndFillPainter(drawBall);
var ball = new Sprite('ball', fillBallPaint);

var fallDownTimer = new Sprite.AnimationTimer();
var translateTimer = new Sprite.AnimationTimer();

//下落行为
ball.addBehavior(function (sprite, behavior, ctx, time ) {
    if(fallDownTimer.isRunning()) {
        time = fallDownTimer.getElapsedTime() / 1000;
        sprite.speed.set({
            x: pixelsPerMeter * time / fps + 10,
            y: GRAVITY_FORCE * time  * pixelsPerMeter / fps
        });
        sprite.y += sprite.speed.y;
        sprite.x += sprite.speed.x;

        if(sprite.y + ballParam.radius >= c.height) {
            fallDownTimer.stop();
            sprite.y = c.height - ballParam.radius;
        }
    }
});

ball.x = 50;
ball.y = 50;

fallDownTimer.start();

(function loop (time) {
    ctx.clearRect(0, 0, c.width, c.height);
    frameAnimationId = requestAnimationFrame(loop);
    var tempFps = stats.update();
    fps = tempFps === 0 ? 60 : tempFps;
    ball.paint(ctx);
    ball.update(ctx);
}());